package cn.fenqing168.springcloud.service.impl;

import cn.fenqing168.springcloud.commons.BaseResult;
import cn.fenqing168.springcloud.dao.OrderDao;
import cn.fenqing168.springcloud.domain.OrderDomain;
import cn.fenqing168.springcloud.entity.OrderEntity;
import cn.fenqing168.springcloud.feign.FeignAccountService;
import cn.fenqing168.springcloud.feign.FeignStorageService;
import cn.fenqing168.springcloud.service.IOrderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 订单服务的实现类
 * @author fenqing
 */
@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private Dao dao;

    @Autowired
    private Feign feign;

    @Component
    class Dao {
        @Autowired
        private OrderDao orderDao;
    }

    @Component
    class Feign {
        @Autowired
        private FeignStorageService feignStorageService;

        @Autowired
        private FeignAccountService feignAccountService;
    }

    @Override
    @GlobalTransactional(name = "tx_test_order_create", rollbackFor = Exception.class)
    public void create(OrderDomain order) {
        order.setStatus(0);
        log.info("#####创建订单");
        OrderEntity orderEntity = new OrderEntity();
        BeanUtils.copyProperties(order, orderEntity);
        dao.orderDao.create(orderEntity);
        log.info("#####创建订单完成");

        log.info("#####减少库存");
        feign.feignStorageService.decrease(orderEntity.getProductId(), orderEntity.getCount());
        log.info("#####减少库存完毕");

        log.info("#####减少库存余额");
        feign.feignAccountService.decrease(orderEntity.getUserId(), orderEntity.getMoney());
        log.info("#####减少库存余额完毕");
        log.info("#####修改订单状态");
        dao.orderDao.updateStatus(orderEntity.getId(), 1);
        log.info("#####修改订单状态完毕");

    }
}
